﻿using B.S.DataBase.MyProject.Domain.RBAC;
using B.S.DataBase.MyProject.Domain.wdx;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using ClosedXML.Excel;
using DocumentFormat.OpenXml.Bibliography;
using MediatR;
using MedicalPCTerminal.Write.API.Appcation.Commands.居民档案PC端;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;


namespace MedicalPCTerminal.Write.API.Controllers
{   
    /// <summary>
    /// 居民档案写控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[Authorize]
    public class ResidentFileController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly SqlSugarContext sqlSugar;
        private readonly ILogger<ResidentFileController> logger;

        public ResidentFileController(IMediator mediator, SqlSugarContext sqlSugar, ILogger<ResidentFileController> logger)
        {
            this.mediator = mediator;
            this.sqlSugar = sqlSugar;
            this.logger = logger;
        }



        /// <summary>
        /// 居民档案添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public Task<APIResult<object>> AddResidentFiles(AddResidentFilesCommand request)
        {
            return mediator.Send(request);
        }


        /// <summary>
        /// 导入居民档案信息
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportResidentFiles(IFormFile file)
        {
            APIResult<int> result = new APIResult<int>();

            try
            {
                // 检查上传文件是否为空
                if (file == null || file.Length <= 0)
                {
                    result.Code = APIEnum.操作失败;
                    result.Msg = "未上传文件或文件为空";
                    return BadRequest(result);
                }

                // 检查文件扩展名是否为 Excel 格式
                var fileExtension = Path.GetExtension(file.FileName).ToLower(); ;
                if (fileExtension != ".xlsx" && fileExtension != ".xls" && fileExtension != ".csv")
                {
                    result.Code = APIEnum.操作失败;
                    result.Msg = "仅支持上传 Excel 文件或CSV文件";
                    return BadRequest(result);
                }

                // 使用 MemoryStream 读取文件内容
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    using (var workbook = new XLWorkbook(stream))
                    {
                        var worksheet = workbook.Worksheet(1); // 获取第一个工作表
                        var rows = worksheet.RowsUsed().Skip(1); // 跳过第一行（表头）

                        List<ResidentFiles> residentFiles = new List<ResidentFiles>();

                        foreach (var row in rows)
                        {
                            var residentFile = new ResidentFiles();

                            residentFile.ResidentFiles_Name = row.Cell(1).GetValue<string>();
                            residentFile.Sex = row.Cell(2).GetValue<bool>();
                            residentFile.Age = row.Cell(3).GetValue<int>();
                            residentFile.CreateTime = DateTime.Now;
                            residentFile.UpdateTime = DateTime.Now;
                            residentFile.IdCard = row.Cell(4).GetValue<string>(); 
                            residentFile.Phone = row.Cell(5).GetValue<string>();
                            residentFile.Birthday = row.Cell(6).GetValue<DateTime>();
                            residentFile.Address = row.Cell(7).GetValue<string>();
                            residentFile.Marriage = row.Cell(8).GetValue<string>();
                            residentFile.BloodType = row.Cell(9).GetValue<string>();
                            residentFile.InsuredSituation = row.Cell(10).GetValue<string>();
                            residentFile.job = row.Cell(11).GetValue<string>();
                            residentFile.Education = row.Cell(12).GetValue<string>();
                            residentFile.IfSmoke = row.Cell(13).GetValue<bool>();
                            residentFile.IfQuitSmoke = row.Cell(14).GetValue<bool>();
                            residentFile.IfPassiveSmoke = row.Cell(15).GetValue<bool>();
                            residentFile.IfDrinkWine = row.Cell(16).GetValue<bool>();
                            residentFile.IfSport = row.Cell(17).GetValue<int>();
                            residentFile.Hypertension = row.Cell(18).GetValue<int>();
                            residentFile.Diabetes = row.Cell(19).GetValue<int>();
                            residentFile.Height = row.Cell(20).GetValue<double>();
                            residentFile.Weight = row.Cell(21).GetValue<double>();
                            residentFile.BMI = Math.Round((double)(residentFile.Weight / Math.Pow((double)(residentFile.Height / 100), 2)), 2);
                            residentFile.Waistline = row.Cell(23).GetValue<double>();
                            residentFile.SystolicPressure = row.Cell(24).GetValue<double>();
                            residentFile.SiastolicPressure = row.Cell(25).GetValue<double>();
                            residentFile.FastingBloodGlucose = row.Cell(26).GetValue<double>();
                            residentFile.CreateUser = row.Cell(28).GetValue<string>();
                            residentFile.UpdateUser = row.Cell(30).GetValue<string>();
                            // 添加到要插入的列表中
                            residentFiles.Add(residentFile);
                        }

                        // 将数据批量插入数据库
                        await sqlSugar.db.Insertable(residentFiles).ExecuteCommandAsync();
                        result.Code = APIEnum.操作成功;
                        result.Msg = APIEnum.操作成功.ToString();
                        result.data = residentFiles.Count;
                    }
                }
            }
            catch (FormatException ex)
            {
                result.Code = APIEnum.操作失败;
                result.Msg = "导入失败，Excel 文件中数据格式错误：" + ex.Message;
                return StatusCode(500, result);
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.操作失败;
                result.Msg = "导入失败，原因：" + ex.Message;
                return StatusCode(500, result);
            }

            return Ok(result);
        }

        /// <summary>
        /// 居民档案信息导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Export()
        {
            byte[] data = null;
            string c = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
            string f = "居民档案信息.xlsx";
            IWorkbook book = new XSSFWorkbook();
            ISheet sheet = book.CreateSheet();
            IRow row1 = sheet.CreateRow(0);
            row1.CreateCell(0).SetCellValue("居民编号");
            row1.CreateCell(1).SetCellValue("姓名");
            row1.CreateCell(2).SetCellValue("性别");
            row1.CreateCell(3).SetCellValue("年龄");
            row1.CreateCell(4).SetCellValue("身份证号");
            row1.CreateCell(5).SetCellValue("联系电话");
            row1.CreateCell(6).SetCellValue("出生日期");
            row1.CreateCell(7).SetCellValue("家庭地址");
            row1.CreateCell(8).SetCellValue("婚姻");
            row1.CreateCell(9).SetCellValue("血型");
            row1.CreateCell(10).SetCellValue("参保情况");
            row1.CreateCell(11).SetCellValue("职业");
            row1.CreateCell(12).SetCellValue("文化程度");
            row1.CreateCell(13).SetCellValue("是否吸烟");
            row1.CreateCell(14).SetCellValue("是否戒烟者");
            row1.CreateCell(15).SetCellValue("是否被动吸烟者");
            row1.CreateCell(16).SetCellValue("是否饮酒");
            row1.CreateCell(17).SetCellValue("是否运动");
            row1.CreateCell(18).SetCellValue("高血压知晓情况");
            row1.CreateCell(19).SetCellValue("糖尿病知晓情况");
            row1.CreateCell(20).SetCellValue("身高");
            row1.CreateCell(21).SetCellValue("体重");
            row1.CreateCell(22).SetCellValue("BMI");
            row1.CreateCell(23).SetCellValue("腰围");
            row1.CreateCell(24).SetCellValue("收缩压");
            row1.CreateCell(25).SetCellValue("舒张压");
            row1.CreateCell(26).SetCellValue("空腹血糖");
            row1.CreateCell(27).SetCellValue("创建时间");
            row1.CreateCell(28).SetCellValue("创建人");
            row1.CreateCell(29).SetCellValue("修改时间");
            row1.CreateCell(30).SetCellValue("修改人");

            var list = sqlSugar.db.Queryable<ResidentFiles>().ToPageList(1, 15);
            int rowIndex = 1;
            foreach (var item in list.ToList())
            {
                IRow row = sheet.CreateRow(rowIndex);
                row.CreateCell(0).SetCellValue(item.ResidentFiles_Id);
                row.CreateCell(1).SetCellValue(item.ResidentFiles_Name);
                row.CreateCell(2).SetCellValue((bool)item.Sex);
                row.CreateCell(3).SetCellValue((int)item.Age);
                row.CreateCell(4).SetCellValue(item.IdCard);
                row.CreateCell(5).SetCellValue(item.Phone);
                row.CreateCell(6).SetCellValue(item.Birthday);
                row.CreateCell(7).SetCellValue(item.Address);
                row.CreateCell(8).SetCellValue(item.Marriage);
                row.CreateCell(9).SetCellValue(item.BloodType);
                row.CreateCell(10).SetCellValue(item.InsuredSituation);
                row.CreateCell(11).SetCellValue(item.job);
                row.CreateCell(12).SetCellValue(item.Education);
                row.CreateCell(13).SetCellValue((bool)item.IfSmoke);
                row.CreateCell(14).SetCellValue((bool)item.IfQuitSmoke);
                row.CreateCell(15).SetCellValue((bool)item.IfPassiveSmoke);
                row.CreateCell(16).SetCellValue((bool)item.IfDrinkWine);
                row.CreateCell(17).SetCellValue((int)item.IfSport);
                row.CreateCell(18).SetCellValue((int)item.Hypertension);
                row.CreateCell(19).SetCellValue((int)item.Diabetes);
                row.CreateCell(20).SetCellValue((double)item.Height);
                row.CreateCell(21).SetCellValue((double)item.Weight);
                row.CreateCell(22).SetCellValue((double)item.BMI);
                row.CreateCell(23).SetCellValue((double)item.Waistline);
                row.CreateCell(24).SetCellValue((double)item.SystolicPressure);
                row.CreateCell(25).SetCellValue((double)item.SiastolicPressure);
                row.CreateCell(26).SetCellValue((double)item.FastingBloodGlucose);
                row.CreateCell(27).SetCellValue(Convert.ToString(item.CreateTime));
                row.CreateCell(28).SetCellValue(item.CreateUser);
                row.CreateCell(29).SetCellValue(Convert.ToString(item.UpdateTime));
                row.CreateCell(30).SetCellValue(item.UpdateUser);
                rowIndex++;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                book.Write(ms);
                data = ms.ToArray();
            }
            return File(data, c, f);
        }


    }
}
